package devicedata

import (
	"context"
	"energy-amiot-platform/core"
	"energy-amiot-platform/model/dbspo"
	"energy-amiot-platform/model/request"
	"energy-amiot-platform/model/response"
	"energy-amiot-platform/utils/respout"
	"errors"

	"github.com/gin-gonic/gin"
)

// @Tags 产品管理
// @Summary 添加一个产品
// @Description 添加一个产品
// @Accept  json
// @Product json
// @Param   name query string false			"产品名称"
// @Param   pageSize query int false		"每页数量" 	default(10)
// @Param   pageNum query int false			"第几页" 	default(1)
// @Success 200 {object} response.Response{result=response.PageData{list=dbspo.Product}} "Ok"
// @Router /product-data/{id} [get]
func pagingQuery(ctx *gin.Context) {
	var handleCode = 2
	var req request.DeviceDataPagingQueryReq
	deviceId := ctx.Param("did")
	if deviceId == "" {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 0, respout.StrErrParse, errors.New("deviceId不能为空"), nil)
		return
	}

	err := ctx.ShouldBindQuery(&req)
	if err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 0, respout.StrErrParse, err, nil)
		return
	}

	switch {
	case req.PageSize == 0:
		req.PageSize = 10
	case req.PageNum == 0:
		req.PageNum = 1
	}

	var count int64
	var result []dbspo.DeviceUpData
	dbc := core.DATABASE.Cur().Model(&dbspo.DeviceUpData{}).Where("device_id=?", deviceId).WithContext(context.Background())
	if err = dbc.Count(&count).Error; err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 1, respout.StrFail, err, nil)
		return
	}

	offset := req.PageSize * (req.PageNum - 1)
	err = dbc.Offset(offset).Limit(req.PageSize).Order("created_at asc").Scan(&result).Error
	if err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 2, respout.StrFail, err, nil)
		return
	}

	respout.Ok(ctx, response.PageData{
		Total: count,
		List:  result,
	})
}
